package edu.spec.basic.dao.impl;

import edu.spec.basic.dao.iface.IUserDao;
import edu.spec.basic.model.User;
import edu.spec.basic.model.dto.UserDto;
import edu.spec.basic.model.enumeration.YesNo;
import org.madgecko.basic.dao.BaseDao;
import org.madgecko.basic.model.Pager;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class UserDao extends BaseDao<User> implements IUserDao {

	@Override
	public User loadByName(String name) {
		String hql = "from User u where u.username=?";
		return (User)this.queryObject(hql, name);
	}

	@Override
	public Pager<User> findUserByCon(Integer status, String con) {
		String hql = "from User u where u.id>" + 0;
		if(status!=null){
			hql += " and u.status=" + status;
		}
		if(con!=null){
			hql += " and (u.username like '%" + con + "%' or u.realName like '%" + con + "%')";
		}
		return this.find(hql);
	}

	@Override
	public List<User> listUserByRole(Integer roleId) {
		//1条sql
		String hql = "select ur.user from UserRole ur where ur.role.id=?";
		return this.list(hql, roleId);
	}

    @Override
    public User loadByOpenId(String openId) {
        String hql = "from User u where u.openId=?";
        return (User)this.queryObject(hql, openId);
    }

    @Override
    public List<Integer> listIdsByFormal(YesNo yesNo) {
        String hql = "select u.id from User u where 1=1 ";
	    if (yesNo!=null){
	        hql += " and u.isFormal=" + yesNo.ordinal();
        }
        return this.listIdByHql(hql);
    }

    @Override
    public List<Integer> listIdsByCommunist(YesNo yesNo) {
        String hql = "select u.id from User u where 1=1 ";
        if (yesNo!=null){
            hql += " and u.isCommunist=" + yesNo.ordinal();
        }
        return this.listIdByHql(hql);
    }

    @Override
    public List<User> listAll() {
	    String hql = "from User";
        return this.list(hql);
    }

    @Override
    public List<User> listUserByIds(String ids) {
        String hql="From User u where u.id in (" + ids + ")";
        return this.list(hql);
    }

    @Override
    public List<UserDto> listUserDtoByIdString(String idString) {
        String hql="select new edu.spec.sys.model.dto.UserDto(u.id, u.realName) from User u where u.id in (" + idString + ")";
        return this.list(hql);
    }

}
